package com.kll.tv.views

import android.content.Intent
import android.view.View
import com.google.i18n.phonenumbers.PhoneNumberUtil
import com.kll.carolinehmibiz.OperationManager
import com.kll.carolinehmibiz.model.AccountModel
import com.kll.carolinehmibiz.model.OperateListener
import com.kll.carolinehmibiz.net.bean.RefreshTokenResponse
import com.kll.carolinehmibiz.presentation.listener.ForgetPasswordProtocol
import com.kll.carolinehmibiz.presentation.presenter.ForgetPasswordPresenter
import com.kll.tv.base.views.BaseActivity
import com.kll.tv.databinding.ActivityForgetPasswordBinding
import com.kll.tv.utils.AppToast
import com.tencent.qcloud.tuicore.util.SoftKeyBoardUtil

/**
 * 忘记密码页
 */
class ForgetPasswordActivity: BaseActivity<ForgetPasswordPresenter>(), ForgetPasswordProtocol.IView {
    private lateinit var binding: ActivityForgetPasswordBinding
    private var mobile = "" // 手机号
    private var verifyCode = "" // 验证码
    private var password = "" // 密码
    private var againPassword = "" // 再一次输入密码

    override fun initViewBinding(): View {
        binding = ActivityForgetPasswordBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun createPresenter(): ForgetPasswordPresenter {
        return ForgetPasswordPresenter(this, this)
    }

    override fun init() {

        initListener()
    }

    private fun initListener() {
        // 获取验证码
        binding.tvGetCheckingCode.setOnClickListener {
            mobile = binding.edtPhoneNumber.text.toString().trim()

            // 判断
            var isValidate = false
            if (mobile.length > 8){
                // 校验手机号码
                isValidate = PhoneNumberUtil.getInstance().isValidNumber(PhoneNumberUtil.getInstance().parse(mobile, "CN"))
            }
            if (!isValidate) {
                AppToast.show("请输入正确的手机号码！", 2000)
                return@setOnClickListener
            }

            mPresenter.getVerifyCode(mobile)
        }

        // 重置密码
        binding.tvSubmit.setOnClickListener {
            mobile = binding.edtPhoneNumber.text.toString().trim()
            verifyCode = binding.edtVerifyCode.text.toString().trim()
            password = binding.edtPassword.text.toString().trim()
            againPassword = binding.edtAgainPassword.text.toString().trim()

            // 判断
            var isValidate = false
            if (mobile.length > 8){
                // 校验手机号码
                isValidate = PhoneNumberUtil.getInstance().isValidNumber(PhoneNumberUtil.getInstance().parse(mobile, "CN"))
            }
            if (!isValidate) {
                AppToast.show("请输入正确的手机号码！", 2000)
                return@setOnClickListener
            }
            if (verifyCode.length < 4) {
                AppToast.show("请输入正确的验证码！", 2000)
                return@setOnClickListener
            }
            if (password.length < 6) {
                AppToast.show("请输入不少于6位数的密码！", 2000)
                return@setOnClickListener
            }

            if (againPassword != password) {
                AppToast.show("两次输入的密码不一致！", 2000)
                return@setOnClickListener
            }

            // 重设
            mPresenter.resetPwd(mobile, verifyCode, password)

        }

        // 去登录
        binding.tvGetLogin.setOnClickListener {
            startActivity(Intent(this, LoginActivity::class.java))
            finish()
        }

        binding.edtVerifyCode.setOnFocusChangeListener(object : View.OnFocusChangeListener {
            override fun onFocusChange(v: View?, hasFocus: Boolean) {
                if (!hasFocus) {
                    SoftKeyBoardUtil.hideKeyBoard(binding.edtVerifyCode.windowToken)
                } else {
                    SoftKeyBoardUtil.showSoftInput(binding.edtVerifyCode)
                }
            }

        })
        binding.edtPhoneNumber.setOnFocusChangeListener(object : View.OnFocusChangeListener {
            override fun onFocusChange(v: View?, hasFocus: Boolean) {
                if (!hasFocus) {
                    SoftKeyBoardUtil.hideKeyBoard(binding.edtPhoneNumber.windowToken)
                } else {
                    SoftKeyBoardUtil.showSoftInput(binding.edtPhoneNumber)
                }
            }

        })
        binding.edtPassword.setOnFocusChangeListener(object : View.OnFocusChangeListener {
            override fun onFocusChange(v: View?, hasFocus: Boolean) {
                if (!hasFocus) {
                    SoftKeyBoardUtil.hideKeyBoard(binding.edtPassword.windowToken)
                } else {
                    SoftKeyBoardUtil.showSoftInput(binding.edtPassword)
                }
            }

        })
        binding.edtAgainPassword.setOnFocusChangeListener(object : View.OnFocusChangeListener {
            override fun onFocusChange(v: View?, hasFocus: Boolean) {
                if (!hasFocus) {
                    SoftKeyBoardUtil.hideKeyBoard(binding.edtAgainPassword.windowToken)
                } else {
                    SoftKeyBoardUtil.showSoftInput(binding.edtAgainPassword)
                }
            }

        })
    }

    /**
     * 重置密码成功
     */
    override fun resetPwdSuccessed() {
        // 跳转到登录页
        AppToast.show("重置密码成功！", 2000)
        startActivity(Intent(this, LoginActivity::class.java))
    }

    /**
     * 重置密码失败
     */
    override fun resetPwdFailed(code: Int, message: String) {
        AppToast.show(message, 2000)
        if (code == 102) {
            // token过期 刷新token
            OperationManager.getInstancce().refreshToken(object : OperateListener {
                override fun onSuccess(state: Int, obj: Any?) {
                    var data = obj as RefreshTokenResponse
                    AccountModel.getInstance(baseContext).updateUserToken(data.token)
                    mPresenter.resetPwd(mobile, verifyCode, password)
                }

                override fun onFail(code: Int, message: String) {
                    AppToast.show(message, 2000)
                    if (code == 101) {
                        loginAgain()
                    }
                }

            })
        }
        if (code == 101) {
            loginAgain()
        }
    }

    /**
     * 发送验证码成功
     */
    override fun sendVerifyCodeSuccessed() {
        AppToast.show("获取验证码成功！", 2000)
    }

    /**
     * 发送验证码失败
     */
    override fun sendVerifyCodeFailed(code: Int, message: String) {
        AppToast.show(message, 2000)
        if (code == 102) {
            // token过期 刷新token
            OperationManager.getInstancce().refreshToken(object : OperateListener {
                override fun onSuccess(state: Int, obj: Any?) {
                    var data = obj as RefreshTokenResponse
                    AccountModel.getInstance(baseContext).updateUserToken(data.token)
                    mPresenter.getVerifyCode(mobile)
                }

                override fun onFail(code: Int, message: String) {
                    AppToast.show(message, 2000)
                    if (code == 101) {
                        loginAgain()
                    }
                }

            })
        }
        if (code == 101) {
            loginAgain()
        }
    }

    /**
     * 更改验证码倒计时UI
     */
    override fun loadAreaCodeTime(count: String, isBusying: Boolean) {
        if (isBusying) {
            binding.tvGetCheckingCode.text = count + "秒后发送"
        } else {
            binding.tvGetCheckingCode.text = count
        }
    }

    override fun showLoading() {

    }

    override fun stopLoading() {

    }
}